package com.wing.productionPlan.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.QRCodeUtil;
import com.wing.config.BaseDataInit;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.entity.ResBenchmarkBookEchnology;
import com.wing.enterprise.product.model.entity.ResBenchmarkBookEchnologyQuality;
import com.wing.enterprise.product.model.response.ProductDetailVO;
import com.wing.enterprise.sell.model.response.OrderVO;
import com.wing.productionPlan.dao.DynamicDao;
import com.wing.productionPlan.dao.ProductionProcessDao;
import com.wing.productionPlan.dao.ProductionWorkOrderDao;
import com.wing.productionPlan.model.entity.*;
import com.wing.productionPlan.model.request.DeviceTypeForm;
import com.wing.productionPlan.model.request.ProductionWorkOrderForm;
import com.wing.productionPlan.model.response.*;
import com.wing.qualityTesting.service.WorkOrderQualityTestingTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static com.wing.productionPlan.model.entity.ProductionTheWorkOrder.Status.sendOver;

/**
 * 生产开工单-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ProductionWorkOrderServiceImpl extends ServiceImpl<ProductionWorkOrderDao, ProductionWorkOrder> implements ProductionWorkOrderService {

    @Autowired
    private ProductionPlanService productionPlanService;
    @Autowired
    private ProductionTheWorkOrderService productionTheWorkOrderService;
    @Autowired
    private ProductionProcessDeviceService productionProcessDeviceService;
    @Autowired
    private ProductionProcessService productionProcessService;
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private EnterpriseClient enterpriseClient;
    @Autowired
    private QualityTestingRecordDetailService qualityTestingRecordDetailService;
    @Autowired
    private ProductionProcessMaterialService productionProcessMaterialService;
    @Autowired
    private WorkOrderQualityTestingTaskService workOrderQualityTestingTaskService;
    @Autowired
    private ProductionProcessDao productionProcessDao;


    @Override
    public int add(ProductionWorkOrderForm productionWorkOrderForm) {

        //校验

        ProductionWorkOrder productionWorkOrder = new ProductionWorkOrder();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(ProductionWorkOrder.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productionWorkOrderForm, productionWorkOrder, copyOptions);

        return baseMapper.insert(productionWorkOrder);
    }

    @Override
    public List<ProductionWorkOrderVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<ProductionWorkOrderVO> pageList4app(Page page, Map<String, Object> params) {
        List<ProductionWorkOrderVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ProductionWorkOrderVO get4appById(Long id, String workOrderCode) {
        return baseMapper.get4appById(id, workOrderCode);
    }

    @Override
    public IPage<ProductionWorkOrderVO> getProductionWorkOrderVOPageList(ProductionWorkOrderVO productionWorkOrderVO, Integer page, Integer limit) {
        IPage<ProductionWorkOrderVO> iPage = new Page<ProductionWorkOrderVO>(page, limit);
        QueryWrapper<ProductionWorkOrder> wrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(productionWorkOrderVO.getDeviceCode())) {
//            wrapper.eq("pwo.device_code", productionWorkOrderVO.getDeviceCode());
//        }

        if (ObjectUtil.isNotEmpty(productionWorkOrderVO.getProcessTypes())) {
            String processTypes = productionWorkOrderVO.getProcessTypes();
            String[] split = processTypes.split(",");
            List<String> strings = Arrays.asList(split);
            wrapper.in("pwo.process_type", strings);

        }
        if (productionWorkOrderVO.getProcessId() != null) {
            wrapper.eq("pwo.process_id", productionWorkOrderVO.getProcessId());
        }

        if (productionWorkOrderVO.getProductionPlanRecordId() != null) {
            wrapper.eq("pwo.production_plan_record_id", productionWorkOrderVO.getProductionPlanRecordId());
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getCode())) {
            wrapper.and(qw -> qw.like("pwo.code", productionWorkOrderVO.getCode()));
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getCode())) {
            wrapper.and(qw -> qw.like("pwo.code", productionWorkOrderVO.getCode()));
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getPlanCode())) {
            wrapper.and(qw -> qw.like("p.code", productionWorkOrderVO.getPlanCode()));
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getSkuName())) {
            wrapper.and(qw -> qw.like("pwo.sku_name", productionWorkOrderVO.getSkuName()));
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getSkuCode())) {
            wrapper.and(qw -> qw.like("pwo.sku_code", productionWorkOrderVO.getSkuCode()));
        }
        // wrapper.eq("t1.status", InventoryInout.Status.valueOf(inventoryInout.getStatus().toString()));
        if (productionWorkOrderVO.getStatus() != null) {
            wrapper.eq("pwo.status", productionWorkOrderVO.getStatus().getValue());
        }
        if (productionWorkOrderVO.getProductTypeId() != null) {
            wrapper.eq("pwo.product_type_id", productionWorkOrderVO.getProductTypeId());
        }
        if (productionWorkOrderVO.getProcessId() != null) {
            wrapper.eq("pwo.process_id", productionWorkOrderVO.getProcessId());
        }
        if (productionWorkOrderVO.getStatusFlag() != null && productionWorkOrderVO.getStatusFlag() == 1) {
            wrapper.in("pwo.status", Arrays.asList(0, 1));
        }

        if (StrUtil.isNotEmpty(productionWorkOrderVO.getKeyword())) {
            wrapper.like("dt.sku_name", productionWorkOrderVO.getKeyword())
                    .or().like("dt.sku_spec", productionWorkOrderVO.getKeyword())
                    .or().like("dt.sku_code", productionWorkOrderVO.getKeyword())
                    .or().like("pwo.process_name", productionWorkOrderVO.getKeyword())
                    //开工单编号
                    .or().like("p.`code`", productionWorkOrderVO.getKeyword())
                    //制造令编号
                    .or().like("pwo.`code`", productionWorkOrderVO.getKeyword());
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getStartCreateTime())) {
            wrapper.ge("pwo.create_time", productionWorkOrderVO.getStartCreateTime());
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getEndCreateTime())) {
            wrapper.le("pwo.create_time", productionWorkOrderVO.getEndCreateTime());
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getWorkshopName())) {
            wrapper.apply("pwo.production_plan_id in (select id from ord_production_plan where workshop_id in (SELECT id from dev_device_workshop WHERE name like CONCAT('%',{0},'%')))", productionWorkOrderVO.getWorkshopName());
        }
        //机型/工种
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getDeviceTypeNames())) {
            List<DeviceOrWorkVo> fessionlist = productionProcessDao.fessionlist(null, productionWorkOrderVO.getDeviceTypeNames());
            String sql = "";
            if (CollectionUtil.isNotEmpty(fessionlist)) {
                int i = 0;
                sql += "(";
                for (DeviceOrWorkVo deviceOrWorkVo : fessionlist) {
                    if (i != 0) {
                        sql += "or";
                    }
                    sql += "FIND_IN_SET(" + deviceOrWorkVo.getId() + ", process.device_types) > 0";
                    i++;
                }
                sql += ")";
            } else {
                List<DeviceOrWorkVo> devicelist = productionProcessDao.devicelist(null, productionWorkOrderVO.getDeviceTypeNames());
                if (CollectionUtil.isNotEmpty(devicelist)) {
                    int i = 0;
                    sql += "(";
                    for (DeviceOrWorkVo deviceOrWorkVo : devicelist) {
                        if (i != 0) {
                            sql += " or ";
                        }
                        sql += "FIND_IN_SET(" + deviceOrWorkVo.getId() + ", process.device_types) > 0";
                        i++;
                    }
                    sql += ")";
                }
            }
            wrapper.apply(sql);
        }
        //工艺编码
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getProcessCode())) {
            wrapper.apply("EXISTS(select 1 from res_benchmark_book_echnology rbe where rbe.code like CONCAT('%',{0},'%') and rbe.id=process.process_id and process.id=pwo.process_id)", productionWorkOrderVO.getProcessCode());
        }
        //计划完工时间
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getStartPredictFinishTime())) {
            wrapper.ge("pwo.predict_finish_time", productionWorkOrderVO.getStartPredictFinishTime());
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getStartPredictFinishTime())) {
            wrapper.le("pwo.predict_finish_time", productionWorkOrderVO.getEndPredictFinishTime());
        }
        //开工时间
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getStartPredictStartTime())) {
            wrapper.ge("pwo.predict_start_time", productionWorkOrderVO.getStartPredictStartTime());
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getEndPredictStartTime())) {
            wrapper.le("pwo.predict_start_time", productionWorkOrderVO.getEndPredictStartTime());
        }
        //交货时间
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getStartShipmentTime())) {
            wrapper.apply("EXISTS(select 1 from ord_production_plan pp where pp.shipment_time >= {0} and pp.id=pwo.production_plan_id)", productionWorkOrderVO.getStartShipmentTime());
        }
        if (StringUtils.isNotEmpty(productionWorkOrderVO.getEndShipmentTime())) {
            wrapper.apply("EXISTS(select 1 from ord_production_plan pp where pp.shipment_time <= {0} and pp.id=pwo.production_plan_id)", productionWorkOrderVO.getEndShipmentTime());
        }
        //wrapper.last("order by pwo.create_time desc,field(pwo.status,2,1,0) desc");
        wrapper.orderByDesc("pwo.`code`");

        baseMapper.getProductionWorkOrderVOPageList(iPage, wrapper);
        return iPage;
    }

    @Transactional
    @Override
    public void moveWorkOrder(Long id, Integer operaType) {
        ProductionWorkOrder workOrder = baseMapper.selectById(id);
        if (workOrder == null) {
            throw new BusinessException("工单不存在");
        }
        //上移
        if (operaType.equals(1)) {
            ProductionWorkOrder upWorkOrder = baseMapper.getUpWorkOrder(workOrder.getNo(), null);
            if (upWorkOrder == null) {
                throw new BusinessException("已是最前面的工单!");
            }
            if (upWorkOrder.getStatus().getValue() == 1) {
                throw new BusinessException("当前上移的工单正在生产中!");
            }
            //交换排序值
            int thisNo = workOrder.getNo();
            workOrder.setNo(upWorkOrder.getNo());
            baseMapper.updateById(workOrder);
            upWorkOrder.setNo(thisNo);
            baseMapper.updateById(upWorkOrder);
            //下移
        } else if (operaType.equals(2)) {
            ProductionWorkOrder nextWorkOrder = baseMapper.getNextWorkOrder(workOrder.getNo(), null);
            if (nextWorkOrder == null) {
                throw new BusinessException("已是最后面的工单!");
            }
            int thisNo = workOrder.getNo();
            workOrder.setNo(nextWorkOrder.getNo());
            baseMapper.updateById(workOrder);
            nextWorkOrder.setNo(thisNo);
            baseMapper.updateById(nextWorkOrder);

        }

    }

    @Override
    public WorkOrderInfoVO getWorkOrderInfo(Long id, Long processId, String skuCode, String deviceCode) {
        WorkOrderInfoVO workOrderInfoVO = new WorkOrderInfoVO();
        //查询设备在产的工单数据
        ProductionWorkOrder workOrder = this.getDeviceProductionOrder(deviceCode);
        if (workOrder != null) {
            id = workOrder.getId();
            processId = workOrder.getProcessId();
        }
        List<ProductionPlanVO> planList = new ArrayList<>();
        ProductionPlanVO planVO = baseMapper.getProductionPlanVOInfo(id);
        //当前工单有计划则查询计划
        if (StringUtils.isNotBlank(planVO.getCode())) {
            //查询销售订单相关数据
            JsonResult<OrderVO> result = enterpriseClient.getOrderById(planVO.getOrderId(), planVO.getCustomerSkuCode());
            if (result.getData() != null) {
                workOrderInfoVO.setDeliveryTime(result.getData().getDeliveryTime());
                workOrderInfoVO.setKeyboarder(result.getData().getCreatorName());
                workOrderInfoVO.setEnquiryAuditPerson(result.getData().getCheckerName());
                workOrderInfoVO.setExpirationDate(result.getData().getOfferEndTime());
                planVO.setDemandQuantity(result.getData().getDemandQuantity());
            }
            planList.add(planVO);
        } else {
            ProductionPlanVO orderInfo = baseMapper.getWorkOrderInfo(id);
            planList.add(orderInfo);
        }
        workOrderInfoVO.setPlanDetail(planList);
        List<ProductionWorkOrderVO> workOrderVOList = baseMapper.getProductionWorkOrderVOList(id);
        //计算设备合格率
        if (workOrderVOList.get(0).getQualifiedQuantity().compareTo(BigDecimal.ZERO) == 1) {
            workOrderVOList.get(0).setDeviceYield(workOrderVOList.get(0).getQualifiedQuantity().divide(workOrderVOList.get(0).getAmount(), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)));
        }

        workOrderInfoVO.setWorkOrderDetail(workOrderVOList);
        List<ProductionProcessMaterialVO> materialVOList = baseMapper.getProductionProcessMaterialVOList(processId, skuCode, id);
        workOrderInfoVO.setMaterialDetail(materialVOList);
        return workOrderInfoVO;
    }

    @Transactional
    @Override
    public void operationWorkOrder(Long id, Long recordId, Integer type) {
        ProductionWorkOrder workOrder = baseMapper.selectById(id);
        //激活
        if (type == 0) {
            //查询工单的工序是否为首 工序
            String processName = workOrder.getProcessName();
            Long bookId = workOrder.getBookId();
            //查询基准书工序信息
            ResBenchmarkBookEchnologyVo resBenchmarkBookEchnologyVo = productionProcessService.getBenEchnologyBy(bookId, processName);
            if (!"0".equals(resBenchmarkBookEchnologyVo.getType())) {
                //判断上条工序是否检开工
                List<ResBenchmarkBookEchnologyVo> echnologyVos = productionProcessService.getBenEchnologyListBy(bookId);
                List<String> collect = echnologyVos.stream().sorted(Comparator.comparing(ResBenchmarkBookEchnologyVo::getSorted)).map(ResBenchmarkBookEchnologyVo::getName).collect(Collectors.toList());
                // 查找选中对象的索引
                int index = collect.indexOf(workOrder.getProcessName());
                if (index > 0) {
                    // 上一道工序的名称
                    String previousProcessName = collect.get(index - 1);
                    QueryWrapper<ProductionWorkOrder> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("process_name", previousProcessName);
                    queryWrapper.eq("production_plan_record_id", recordId);
                    queryWrapper.eq("book_id", bookId);
                    ProductionWorkOrder one = this.getOne(queryWrapper);
                    if (one.getStatus().equals(ProductionWorkOrder.Status.toactivate)) {
                        throw new BusinessException("当前工序非首工序 需等待上一道工序的开工单激活才能开始下一道工序!");
                    }
                    //如果上一道工序没有可领用数量
                    if (one.getCanGetQuantity() <= 0) {
                        throw new BusinessException("上一道工序无可领用数量!");
                    }
                }
            }
            workOrder.setStatus(ProductionWorkOrder.Status.inproduction);
            //初始化本道工序的可认领数量
//            workOrder.setCanGetQuantity(workOrder.getOutputQuantity());

        } else if (type == 1) {
            workOrder.setStatus(ProductionWorkOrder.Status.toactivate);
        } else if (type == 2) {
            //如果工单状态是生产中 不能关闭
            if (workOrder.getStatus().getValue() == 1) {
                throw new BusinessException("当前工单在生产中不能关闭!");
            }
            workOrder.setStatus(ProductionWorkOrder.Status.accomplish);
        }
        baseMapper.updateById(workOrder);
    }

    @Override
    public ProductionWorkOrder getDeviceProductionOrder(String deviceCode) {
        LambdaQueryWrapper<ProductionWorkOrder> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(ProductionWorkOrder::getDeviceCode, deviceCode);
        wrapper.eq(ProductionWorkOrder::getStatus, 1);
        ProductionWorkOrder productionWorkOrder = baseMapper.selectOne(wrapper);
        return productionWorkOrder;
    }

    @Transactional
    @Override
    public void submitWorkOrder(ProductionWorkOrderForm productionWorkOrderForm) {
        if (productionWorkOrderForm == null) {
            throw new BusinessException("参数异常");
        }
        ProductionPlanVO planVO = productionPlanService.get4appById(productionWorkOrderForm.getProductionPlanId());
        String skuName = planVO.getCustomerSkuName();
        String skuSpec = planVO.getCustomerSkuSpec();
        String unitName = planVO.getUnitName();
        String productTypeName = planVO.getProductTypeName();
        Long productTypeId = planVO.getProductTypeId();
        String enterpriseCode = BaseDataInit.ENTERPRISE_DATA.getCode();

        //生产开工单
        ProductionWorkOrder workOrder = new ProductionWorkOrder();
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        Integer maxNo = dynamicDao.getMaxNo("ord_production_work_order");
        String code = CodeUtil.getCode(maxNo);
        workOrder.setNo(Integer.valueOf(code));
        workOrder.setCode("GD" + today + code);
        workOrder.setDay(Integer.valueOf(today));
        workOrder.setEnterpriseCode(enterpriseCode);
        workOrder.setProcessId(productionWorkOrderForm.getProductionProcessId());
        workOrder.setProcessName(productionWorkOrderForm.getProcessName());
        workOrder.setProductionPlanId(productionWorkOrderForm.getProductionPlanId());
        workOrder.setProductionPlanRecordId(productionWorkOrderForm.getProductionPlanRecordId());
        workOrder.setSkuCode(productionWorkOrderForm.getSkuCode());
        workOrder.setProductionQuantity(productionWorkOrderForm.getProductionQuantity());
        workOrder.setOutputQuantity(productionWorkOrderForm.getOutputQuantity());
        workOrder.setProductDetailId(productionWorkOrderForm.getProductDetailId());
//        workOrder.setSkuName(skuName);
//        workOrder.setSkuSpec(skuSpec);
//        workOrder.setUnitName(unitName);
//        workOrder.setProductTypeName(productTypeName);
//        workOrder.setProductTypeId(productTypeId);
        workOrder.setStatus(ProductionWorkOrder.Status.toactivate);
        workOrder.setWorkOrderQuality(productionWorkOrderForm.getWorkOrderQuality());
        this.save(workOrder);

        //更新制造令已排产数量
//        ProductionProcessDevice processDevice = productionProcessDeviceService.getById(productionWorkOrderForm.getProductionProcessDeviceId());
//        processDevice.setOutputQuantity(processDevice.getOutputQuantity() + productionWorkOrderForm.getOutputQuantity());
//        productionProcessDeviceService.updateById(processDevice);
    }

    @Override
    public ProductionWorkOrderVO getWorkOrderDetails(Long workOrderId, String workOrderCode) {
        ProductionWorkOrderVO workOrderDetails = baseMapper.getWorkOrderDetails(workOrderId, workOrderCode);
        if (ObjectUtil.isEmpty(workOrderDetails)) {
            throw new BusinessException("工单编号不存在！");
        }
        //查询工序设备信息
        Long processId = workOrderDetails.getProcessId();
        if (ObjectUtil.isNotEmpty(processId)) {
            ProductionProcess byId = this.productionProcessService.getById(processId);
            if (ObjectUtil.isNotEmpty(byId)) {
                if (StrUtil.isNotBlank(byId.getDeviceTypes())) {
                    List<String> list = Arrays.asList(byId.getDeviceTypes().split(","));
                    List<DeviceTypeForm> deviceTypeFormList = this.productionProcessService.getDevicetTypeList(list);
                    workOrderDetails.setDeviceTypeList(deviceTypeFormList);
                }
            }
        }

        Map<String, Object> map = qualityTestingRecordDetailService.getProcessOutputAndYield(workOrderDetails.getProcessId(), null);
        workOrderDetails.setYield(map.get("yield").toString());
        return workOrderDetails;

    }

    @Override
    public IPage<ProductionWorkStationVO> getProductionWorkStationVOPageList(Integer page, Integer limit) {
        IPage<ProductionWorkStationVO> iPage = new Page<>(page, limit);
        //基准书信息
        return baseMapper.getProductionWorkStationVOPageList(iPage);
    }

    /**
     * 获取工单信息
     *
     * @param orderId 工单id
     * @return
     */
    @Override
    public ProductionWorkOrderDetailVO getDetailBy(Long orderId) {
        ProductionWorkOrderDetailVO byId = new ProductionWorkOrderDetailVO();
        ProductionWorkOrder vo = this.getByInfoBy(orderId);
        BeanUtil.copyProperties(vo, byId);
        if (ObjectUtil.isNotEmpty(byId)) {
            //查询工序对应的信息
            ProductionProcess productProcess = this.productionProcessService.getById(byId.getProcessId());

            if (ObjectUtil.isNotEmpty(productProcess)) {
                ProductionPlan id = productionPlanService.getById(productProcess.getProductionPlanId());
                if (ObjectUtil.isNotEmpty(id)) {
                    byId.setProductionPlanCode(id.getCode());
                }
                List<DrawInfosVO> drawInfosVos = this.baseMapper.getDrawInfosBy(vo.getBookId());
                if (ObjectUtil.isNotEmpty(drawInfosVos)) {
                    byId.setDrawInfos(drawInfosVos);
                }
                //查询出工序对应的工序成品物料信息
                Long processId = productProcess.getProcessId();
//                List<ResBenchmarkBookEchnologyQuality> qualityList = enterpriseClient.getQualityInfoBy(byId.getBookId(),processId);
                List<ResBenchmarkBookEchnologyQuality> qualityList = this.baseMapper.getQualityInfoBy(byId.getBookId(), processId);
                byId.setQualityList(qualityList);

                String deviceTypes = productProcess.getDeviceTypes();
                List<String> strings = Arrays.asList(deviceTypes.split(","));


                //查询工序相关信息
                // ResBenchmarkBookEchnology echnology = enterpriseClient.getProcessInfoByProcessId(processId);
                ResBenchmarkBookEchnology echnology = this.baseMapper.getProcessInfoByProcessId(processId);
                if (ObjectUtil.isNotEmpty(echnology)) {
                    byId.setWorkstationNature(echnology.getWorkstationNature());
                    byId.setWorkstationNatureName(MaintenanceEnum.workstationEmum.getNameByCode(echnology.getWorkstationNature()));
                    byId.setType(echnology.getType());
                    byId.setTypeName(echnology.getTypeName());
                    byId.setUnitId(echnology.getUnitId());
                    byId.setQualityNature(echnology.getQualityNature());
                    byId.setContent(echnology.getContent());
                    byId.setQualityNatureName(echnology.getQualityNatureName());
                    //设备工位
                    if (MaintenanceEnum.workstationEmum.SBGW.getCode().equals(echnology.getWorkstationNature())) {
                        List<DeviceOrWorkVo> devicelist = productionProcessService.devicelist(strings);
                        byId.setDeviceTypeList(devicelist);
                    } else {
                        List<DeviceOrWorkVo> fessionlist = productionProcessService.fessionlist(strings);
                        byId.setDeviceTypeList(fessionlist);
                    }
                }
            }

            if (StrUtil.isNotEmpty(byId.getSkuCode())) {


                ProductDetailVO data = this.baseMapper.getProductDetailBySkuCode(byId.getSkuCode());
                if (data != null) {
                    byId.setSkuSpec(data.getSkuSpec());
                    byId.setSkuCode(data.getSkuCode());
                    byId.setSkuName(data.getSkuName());
                }
            }

            //查询出设备类型组
            QueryWrapper<ProductionProcessMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("plan_record_id", byId.getProductionPlanRecordId());
            queryWrapper.eq("process_id", byId.getProcessId());
            //查询物料信息
            List<ProductionProcessMaterial> list = this.productionProcessMaterialService.list(queryWrapper);
            byId.setSkuList(list);

            //查询上一组工序的信息（非首工序）
            if (!MaintenanceEnum.gxTypeEmum.SGX.getCode().equals(byId.getType())) {
                if (ObjectUtil.isNotEmpty(vo)) {
                    Integer sorted = vo.getSorted();
                    if (ObjectUtil.isNotEmpty(sorted)) {
                        //查询上一道工序的信息
                        Long productionPlanRecordId = vo.getProductionPlanRecordId();
                        QueryWrapper<ProductionWorkOrder> wrapper = new QueryWrapper<>();
                        wrapper.eq("production_plan_record_id", productionPlanRecordId);
                        wrapper.eq("sorted", --sorted);
                        ProductionWorkOrder productionWorkOrder = this.baseMapper.selectOne(wrapper);
                        if (ObjectUtil.isNotEmpty(productionWorkOrder)) {
                            byId.setPreviousAcceptanceQuantity(productionWorkOrder.getAcceptanceQuantity());
                            byId.setPreviousRepairsQuantity(productionWorkOrder.getRepairsQuantity());
                            byId.setPreviousGetQuantity(productionWorkOrder.getGetQuantity());
                            byId.setPreviousReportedQuantity(productionWorkOrder.getReportedQuantity());
                            byId.setPreviousScrapQuantity(productionWorkOrder.getScrapQuantity());
                        }
                    }
                }
            }

        }
        return byId;
    }

    @Override
    public Long getProcessIdForWork(Long workId) {
        return baseMapper.getProcessIdForWork(workId);
    }

    /**
     * 查询当前开工单是否需要质检
     *
     * @param workOrderId
     * @return
     */
    @Override
    public String getIsNeedQuality(Long workOrderId) {
        return baseMapper.getIsNeedQuality(workOrderId);
    }

    @Override
    public String getQualityAttributes(Long workOrderId) {
        return baseMapper.getQualityAttributes(workOrderId);
    }

    /**
     * 查詢工序類型
     *
     * @param workOrderId
     * @return
     */
    @Override
    public String getTypeLies(Long workOrderId) {
        return baseMapper.getTypeLies(workOrderId);
    }

    /**
     * 查询上一道工序的一些信息
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, Object> getUpOneInfo(Long orderId) {
        return baseMapper.getUpOneInfo(orderId);
    }

    /**
     * 查询工艺流程卡信息
     *
     * @param id
     * @return
     */
    @Override
    public ProcessCardInfoVo getProcessCardBy(Long id) {
        ProcessCardInfoVo cardInfoVo = this.productionTheWorkOrderService.getCardInfoBy(id);
        if (ObjectUtil.isNotEmpty(cardInfoVo)) {
            //设置二维码
            QrConfig config = new QrConfig(110, 110);
            // 设置边距，既二维码和背景之间的边距
            config.setMargin(3);
            // 设置前景色，既二维码颜色（青色）
            config.setForeColor(Color.black.getRGB());
            // 设置背景色（灰色）
            config.setBackColor(Color.WHITE.getRGB());
            String qrCode;
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                // 生成二维码到文件，也可以到流
                QrCodeUtil.generate(cardInfoVo.getCode(), config, ImgUtil.IMAGE_TYPE_PNG, outputStream);
                byte[] pngData = outputStream.toByteArray();
                qrCode = "data:image/png;base64," + Base64.encode(pngData);
                cardInfoVo.setCardPrCord(qrCode);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //查看订单是否为空
            if (ObjectUtil.isNotEmpty(cardInfoVo.getOrderId())) {
                //1.根据类型判断 查询订单code
                if (cardInfoVo.getOrderType().equals(ProductionPlan.OrderType.finish.getValue().toString())) {
                    //查询订单id
                    String infoCode = this.productionPlanService.getFinishCodeBy(cardInfoVo.getOrderId());
                    cardInfoVo.setOrderCode(infoCode);
                } else if (ProductionPlan.OrderType.order.getValue().toString().equals(cardInfoVo.getOrderType())) {
                    String infoCode = this.productionPlanService.getOrderCodeBy(cardInfoVo.getOrderId());
                    cardInfoVo.setOrderCode(infoCode);
                }
            }
            //2.查询开工单工序
            List<ProductionWorkOrderInfoVo> list = this.baseMapper.getWorkOrderInfosBy(cardInfoVo.getId());
            if (CollectionUtil.isNotEmpty(list)) {

                List<DeviceOrWorkVo> fessionlist = productionProcessService.fessionlist(null);
                List<DeviceOrWorkVo> devicelist = productionProcessService.devicelist(null);
                for (ProductionWorkOrderInfoVo productionWorkOrderInfoVo : list) {
                    String workQrCode;
                    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                        // 生成二维码到文件，也可以到流
                        QrCodeUtil.generate(productionWorkOrderInfoVo.getCode(), config, ImgUtil.IMAGE_TYPE_PNG, outputStream);
                        byte[] pngData = outputStream.toByteArray();
                        workQrCode = "data:image/png;base64," + Base64.encode(pngData);
                        productionWorkOrderInfoVo.setProcessPrCode(workQrCode);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    //判断是人工工位 还是设备工位
                    //1.设备工位
                    if (productionWorkOrderInfoVo.getWorkstationNature().equals(MaintenanceEnum.workstationEmum.SBGW.getCode())) {
                        for (DeviceOrWorkVo deviceOrWorkVo : devicelist) {
                            if (deviceOrWorkVo.getId().equals(productionWorkOrderInfoVo.getDeviceType())) {
                                productionWorkOrderInfoVo.setDeviceTypeName(deviceOrWorkVo.getDeviceName());
                            }
                        }
                    }
                    //人工工位
                    else {
                        for (DeviceOrWorkVo deviceOrWorkVo : fessionlist) {
                            if (deviceOrWorkVo.getId().equals(productionWorkOrderInfoVo.getDeviceType())) {
                                productionWorkOrderInfoVo.setDeviceTypeName(deviceOrWorkVo.getDeviceName());
                            }

                            if (deviceOrWorkVo.getId().equals(productionWorkOrderInfoVo.getPersonnelWorkType())) {
                                productionWorkOrderInfoVo.setPersonnelWorkTypeName(deviceOrWorkVo.getDeviceName());
                            }
                        }
                    }
                }
            }
            cardInfoVo.setWorkOrderInfoVoList(list);
            return cardInfoVo;
        }
        return cardInfoVo;
    }

    /**
     * 查询开工单打印信息
     *
     * @param id
     * @return
     */
    @Override
    public ProWorkOrderPrintVo getWorkOrderPrint(Long id) {
        //设置二维码
        QrConfig config = new QrConfig(110, 110);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(3);
        // 设置前景色，既二维码颜色（青色）
        config.setForeColor(Color.black.getRGB());
        // 设置背景色（灰色）
        config.setBackColor(Color.WHITE.getRGB());

        ProWorkOrderPrintVo proWorkOrderPrintVo = productionTheWorkOrderService.getWorkOrderPrint(id);

        if (ObjectUtil.isNotEmpty(proWorkOrderPrintVo)) {
            //查看订单是否为空
            if (ObjectUtil.isNotEmpty(proWorkOrderPrintVo.getOrderId())) {
                //1.根据类型判断 查询订单code
                if (proWorkOrderPrintVo.getOrderType().equals(ProductionPlan.OrderType.finish.getValue().toString())) {
                    //查询订单id
                    String infoCode = this.productionPlanService.getFinishCodeBy(proWorkOrderPrintVo.getOrderId());
                    proWorkOrderPrintVo.setOrderCode(infoCode);
                } else if (ProductionPlan.OrderType.order.getValue().toString().equals(proWorkOrderPrintVo.getOrderType())) {
                    String infoCode = this.productionPlanService.getOrderCodeBy(proWorkOrderPrintVo.getOrderId());
                    proWorkOrderPrintVo.setOrderCode(infoCode);
                }
            }
            //查詢工序信息
            ProductionWorkOrderInfoVo infoVo = this.baseMapper.getWorkOrderInfoAaaBy(id);
            List<DeviceOrWorkVo> fessionlist = productionProcessService.fessionlist(null);
            List<DeviceOrWorkVo> devicelist = productionProcessService.devicelist(null);

            //查詢圖紙列表
            List<String> strings = this.baseMapper.getDrawUrls(proWorkOrderPrintVo.getBookId());
            proWorkOrderPrintVo.setDrawUrls(strings);

            String workQrCode;
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                // 生成二维码到文件，也可以到流
                QrCodeUtil.generate(proWorkOrderPrintVo.getWorkOrderCode(), config, ImgUtil.IMAGE_TYPE_PNG, outputStream);
                byte[] pngData = outputStream.toByteArray();
                workQrCode = "data:image/png;base64," + Base64.encode(pngData);
                proWorkOrderPrintVo.setCardCode(workQrCode);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //判断是人工工位 还是设备工位
            //1.设备工位
            if (infoVo.getWorkstationNature().equals(MaintenanceEnum.workstationEmum.SBGW.getCode())) {
                for (DeviceOrWorkVo deviceOrWorkVo : devicelist) {
                    if (deviceOrWorkVo.getId().equals(infoVo.getDeviceType())) {
                        infoVo.setDeviceTypeName(deviceOrWorkVo.getDeviceName());
                    }
                }
            }
            //人工工位
            else {
                for (DeviceOrWorkVo deviceOrWorkVo : fessionlist) {
                    if (deviceOrWorkVo.getId().equals(infoVo.getDeviceType())) {
                        infoVo.setDeviceTypeName(deviceOrWorkVo.getDeviceName());
                    }

                    if (deviceOrWorkVo.getId().equals(infoVo.getPersonnelWorkType())) {
                        infoVo.setPersonnelWorkTypeName(deviceOrWorkVo.getDeviceName());
                    }
                }
            }
            BeanUtil.copyProperties(infoVo, proWorkOrderPrintVo);
            return proWorkOrderPrintVo;
        }
        return null;
    }

    /**
     * 获取末工序的报工数量
     * @param productionPlanRecordId
     * @return
     */
    @Override
    public Integer getLastReportInfoBy(Long productionPlanRecordId) {
        return this.baseMapper.getLastReportInfoBy(productionPlanRecordId);
    }

    /**
     * 查询开工单信息
     *
     * @param orderId
     * @return
     */
    private ProductionWorkOrder getByInfoBy(Long orderId) {
        return baseMapper.getByInfoBy(orderId);
    }
}
